#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

class Sock
{
public:
    static int Socket()
    {
        int listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if (listen_sock < 0)
        {
            std::cerr << "socket failed" << std::endl;
            exit(2);
        }
        int opt = 1;
        setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        return listen_sock;
    }

    static void Bind(int sock, uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(sock, (struct sockaddr *)&local, sizeof(local)) == -1)
        {
            std::cerr << "bind failed" << std::endl;
            exit(3);
        }
    }

    static void Listen(int sock)
    {
        if (listen(sock, 5) == -1)
        {
            std::cerr << "listen failed" << std::endl;
            exit(4);
        }
    }

    static int Accept(int sock)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        memset(&client, 0, sizeof(client));

        int new_sock = accept(sock, (struct sockaddr *)&client, &len);
        if (new_sock == -1)
        {
            std::cerr << "accept failed" << std::endl;
            exit(5);
        }
        return new_sock;
    }

    static void Connect(int sock, std::string ip, uint16_t port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));

        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        server.sin_addr.s_addr = inet_addr(ip.c_str());
        if (connect(sock, (struct sockaddr *)&server, sizeof(server)) == -1)
        {
            std::cerr << "connect failed" << std::endl;
            exit(6);
        }
    }
};